import * as step from '@flow-step/step-toolkit'
import process from 'process'
import {getParams} from './params'

export function run() {
    step.info('execute command run ...')

    // 获取回调地址，将回调地址传递给第三方系统，在第三方系统任务执行完回调时使用
    const callbackUrl = step.callbackUrl()
    step.info("You can POST callbackUrl to trigger job continue to run")
    step.info("callbackUrl: " + callbackUrl)

    // 【TODO】实现你的自定义逻辑: 将上述 callbackUrl 作为额外参数，触发第三方系统生成部署单、审批流程等业务逻辑

    // optional: 支持输出变量传递给后续运行实例
    step.interaction.saveEnvVar("custom_env_key", "custom_env_value")

    // 在任务卡片运行状态下，展示提示信息
    step.interaction.appendMessage("Message: Wait Callback")

    const actions = [];
    actions.push({
        type: step.interaction.ACTION_TYPE_HIDDEN,     // HIDDEN 或 EXECUTE
        action: 'CALLBACK',  // 下一次运行实例的 command 入参
        name: '第三方回调',
        order: 1
    })
    step.interaction.appendActions(actions)

    step.info('job run to wait')
}

export function callback() {
    step.info('execute command callback ...')

    // 【TODO】实现你的自定义逻辑: 通过卡片展示信息、链接等; 决定任务运行成功或失败

    // optional: 访问前序任务实例传递的变量
    step.info(`env passed from before job instance custom_env_key=:${process.env["custom_env_key"]}`)

    // 在运行任务卡片上展示链接
    step.interaction.addLink("第三方提示链接", "https://www.aliyun.com/product/yunxiao")

    // 在运行任务卡片上展示提示信息
    // case A: 任务成功时展示
    step.interaction.appendSummaryInfo("I am title...", "I am message...")
    step.info('job run to completed')

    // case B: 任务失败时展示
    // step.interaction.appendErrorMessage("Error Message: Wait Callback")
    // step.info('job run to failed')
    // throw new Error('Error: Wait Callback')
}

async function runStep(): Promise<void> {
    const params = getParams()
    step.info(`PIPELINE_ID=${params.pipelineID}`)
    step.info(`PIPELINE_NAME=${params.pipelineName}`)
    step.info(`BUILD_NUMBER=${params.buildNumber}`)
    step.info(`WORK_SPACE=${params.workSpace}`)
    step.info(`PROJECT_DIR=${params.projectDir}`)
    step.info(`BUILD_JOB_ID=${params.buildJobID}`)

    const command = process.env['COMMAND']
    switch (command) {
        case 'RUN':
            run();
            break;
        case 'CALLBACK':
            callback();
            break;
        default:
            throw new Error('Invalid action. Please provide Run .')
    }
}

runStep()
    .then(function () {
        step.success('run step successfully!')
    })
    .catch(function (err: Error) {
        step.error(err.message)
        process.exit(-1)
    })
